package com.jiazhong.example.project.bookstore.front.interceptor;

import com.jiazhong.example.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.example.project.bookstore.commons.handler.NotLoginException;
import com.jiazhong.example.project.bookstore.commons.util.ResultTool;
import com.jiazhong.example.project.bookstore.front.service.impl.UserServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            throw new NotLoginException("用户没有登陆");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        String redisToken = forValue.get(UserServiceImpl.LOGIN_PREFIX + userId);
        if (!Objects.equals(redisToken, token)) {
            throw new NotLoginException("用户没有登陆");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
